package cn.yunyichina.provider.cashpool.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cn.yunyichina.provider.cashpool.dao.CouponCodeDao;
import cn.yunyichina.provider.cashpool.entity.CouponCode;
import cn.yunyichina.provider.cashpool.vo.CouponCodeVo;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.framework.utils.UUIDUtil;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;

@Service("couponcodeServiceImpl")
public class CouponCodeServiceImpl {
    private Logger logger = LoggerFactory.getLogger(CouponCodeServiceImpl.class);

    @Autowired
    private CouponCodeDao couponCodeDao;

    /**
     * 获取券码列表 - yyt.cashpool.couponcode.list
     * 
     * @param json
     * @param sessionId
     * @return
     */
    public Response listCouponcode(String json, String sessionId) {
        logger.info("listCouponcode start json=" + json);
        Response response = new Response();

        try {
            CouponCodeVo couponCodeVo = JsonUtils.parseObject(json, CouponCodeVo.class);
            List<String> orderColumns = new ArrayList<String>();
            orderColumns.add("create_time");

            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNum(couponCodeVo.getPageNum());
            pageInfo.setPageSize(couponCodeVo.getPageSize());

            Map<String, Object> map = new HashMap<String, Object>();

            CouponCode wheres = new CouponCode();
            if (StringUtils.isNotBlank(couponCodeVo.getCouponId())) {
                wheres.setCouponId(couponCodeVo.getCouponId());
            }
            if (StringUtils.isNotBlank(couponCodeVo.getCouponCode())) {
                wheres.setCouponCode(couponCodeVo.getCouponCode());
            }
            if (couponCodeVo.getIsPushed() != null) {
                wheres.setIsPushed(couponCodeVo.getIsPushed());
            }
            List<CouponCode> couponCodes = couponCodeDao.select(wheres, null, orderColumns, false, pageInfo);
            map.put("couponCodes", couponCodes);

            long couponCodesCount = couponCodeDao.selectCount(wheres);
            map.put("count", couponCodesCount);

            response.setResult(JsonUtils.toJsonString(map));
        } catch (Exception e) {
            logger.error("listCouponcode error", e);
            return Response.failure();
        }

        logger.info("listCouponcode response=" + JSON.toJSONString(response));
        return response;
    }

    /**
     * 删除券码列表 - yyt.cashpool.couponcode.delete
     * 
     * @param json
     * @param sessionId
     * @return
     */
    public Response deleteCouponcode(String json, String sessionId) {
        logger.info("deleteCouponcode start json=" + json);
        Response response = new Response();

        try {
            CouponCodeVo couponCodeVo = JsonUtils.parseObject(json, CouponCodeVo.class);
            String ids = couponCodeVo.getId();
            List<String> list = new ArrayList<String>();
            if (ids.contains(",")) {
                String[] idsArray = ids.split(",");
                list = Arrays.asList(idsArray);
            } else {
                list.add(ids);
            }
            logger.info("deleteCouponcode delete request=" + JSON.toJSONString(list));
            couponCodeDao.deleteByIds(list);
        } catch (Exception e) {
            logger.error("deleteCouponcode error", e);
            return Response.failure();
        }

        logger.info("deleteCouponcode response=" + JSON.toJSONString(response));
        return response;
    }

    /**
     * 导入券码 - yyt.cashpool.couponcode.import
     * 
     * @param json
     * @param sessionId
     * @return
     */
    public Response importCouponcode(String json, String sessionId) {
        logger.info("importCouponcode start json=" + json);
        try {
            CouponCodeVo couponCodeVo = JsonUtils.parseObject(json, CouponCodeVo.class);
            List<CouponCode> records = new ArrayList<CouponCode>();
            String codes = couponCodeVo.getCouponCode();
            List<String> list = new ArrayList<String>();
            if (codes.contains(",")) {
                String[] codesArray = codes.split(",");
                list = Arrays.asList(codesArray);
            } else {
                list.add(codes);
            }

            for (String code : list) {
                CouponCode record = new CouponCode();
                record.setCouponId(couponCodeVo.getCouponId());
                record.setCouponCode(code);
                record.setId(UUIDUtil.get32UUID());
                record.setIsPushed(0);
                record.setIsReceived(0);
                record.setCreateTime(DateUtils.dateToString(new Date()));
                records.add(record);
            }
            logger.info("couponCodeDao insert request=" + JSON.toJSONString(records));
            couponCodeDao.batchInsert(records);
        } catch (Exception e) {
            logger.error("importCouponcode error", e);
            return Response.failure();
        }
        return Response.success();
    }

    /**
     * 获取我的券码列表 - yyt.cashpool.couponcode.by.openid.list
     * 
     * @param json
     * @param sessionId
     * @return
     */
    public Response listCouponcodeByOpenid(String json, String sessionId) {
        logger.info("listCouponcodeByOpenid start json=" + json);
        Response response = new Response();

        try {
            CouponCodeVo couponCodeVo = JsonUtils.parseObject(json, CouponCodeVo.class);
            List<String> orderColumns = new ArrayList<String>();
            orderColumns.add("create_time");

            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNum(couponCodeVo.getPageNum());
            pageInfo.setPageSize(couponCodeVo.getPageSize());

            Map<String, Object> map = new HashMap<String, Object>();

            CouponCode wheres = new CouponCode();
            if (StringUtils.isNotBlank(couponCodeVo.getOpenId())) {
                wheres.setOpenId(couponCodeVo.getOpenId());
            } else {
                return Response.failure();
            }
            wheres.setCreateTime(DateUtils.dateToString(new Date()));
            List<Map<String, Object>> datamaps = couponCodeDao.selectMyCoupon(wheres, null, orderColumns, false,
                    pageInfo);
            map.put("couponCodes", datamaps);

            long couponCodesCount = couponCodeDao.selectMyCouponCount(wheres);
            map.put("count", couponCodesCount);

            response.setResult(JsonUtils.toJsonString(map));
        } catch (Exception e) {
            logger.error("listCouponcodeByOpenid error", e);
            return Response.failure();
        }

        logger.info("listCouponcodeByOpenid response=" + JSON.toJSONString(response));
        return response;
    }
}
